<script setup lang="ts">
import { useUserStore } from "@/store/modules/user"
import { reactive, ref } from "vue"
import { IStudentInfoData } from "@/api/login/types/login"
import { ElLoading, FormInstance, FormRules, genFileId, UploadInstance, UploadProps, UploadRawFile } from "element-plus"
import { Plus, Switch, Upload } from "@element-plus/icons-vue"
import { resetPasswordApi, uploadHeadImageApi, uploadIdentificationPhoto } from "@/api/student"
import { showPromptMessage } from "@/utils"
import { VueCropper } from "vue-cropper"
import "vue-cropper/dist/index.css"

const userStore = useUserStore()
const userInfo = ref<IStudentInfoData>()
userInfo.value = userStore.userInfo as IStudentInfoData
const imageUrl = ref<string | undefined>("")
const uploadRef = ref<UploadInstance | null>(null)
const dialogVisible = ref(false)
const fullLoading = ref<any>(null)

const handleExceed: UploadProps["onExceed"] = (files) => {
  uploadRef.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  uploadRef.value!.handleStart(file)
}

const handleConfirm = async () => {
  if (imageUrl.value) {
    fullLoading.value = ElLoading.service({
      lock: true,
      text: "上传中..."
    })
    const formData = new FormData()
    if (fileList.value[0]) {
      formData.append("file", fileList.value[0])
      const res = await uploadIdentificationPhoto(formData)

      if (res.code === 200) {
        uploadHeadImageApi({
          identificationPhotoUrl: res.data.url,
          identityCardId: userInfo.value!.identityCardId
        })
          .then(() => {
            showPromptMessage("success", "上传成功")
            dialogVisible.value = false
            userStore.getUserInfo()
          })
          .finally(() => {
            dialogVisible.value = false
            fullLoading.value?.close()
          })
      }
      fullLoading.value?.close()
    }
  }
}

const passwordFormRef = ref<FormInstance>()
const changePasswordData = ref<{
  newPass: string
  confirm: string
}>({
  newPass: "",
  confirm: ""
})
const passwordDialogVisible = ref(false)
const rules = reactive<FormRules>({
  newPass: [{ required: true, message: "请输入新密码", trigger: "blur" }],
  confirm: [{ required: true, message: "请确认密码", trigger: "blur" }]
})
const handleChangePassword = () => {
  if (changePasswordData.value.confirm !== changePasswordData.value.newPass) {
    changePasswordData.value.confirm = ""
    return showPromptMessage("error", "两次密码不一致")
  }
  passwordFormRef.value?.validate((valid) => {
    if (valid) {
      resetPasswordApi({ password: changePasswordData.value.newPass, identityCardId: userInfo.value!.identityCardId })
        .then(() => {
          showPromptMessage("success", "修改成功")
        })
        .finally(() => {
          passwordDialogVisible.value = false
        })
    } else {
      return false
    }
  })
}

const resetPasswordForm = () => {
  passwordFormRef.value?.resetFields()
}

const open = ref(false)
const visible = ref(false)
const cropper = ref()
//图片裁剪数据
const options = reactive<any>({
  img: "", // 裁剪图片的地址
  autoCrop: true, // 是否默认生成截图框
  autoCropWidth: 350, // 默认生成截图框宽度
  autoCropHeight: 530, // 默认生成截图框高度
  fixedBox: true, // 固定截图框大小 不允许改变
  outputType: "png", // 默认生成截图为PNG格式
  previews: {} //预览数据
})

const fileList = ref<Blob[]>([])
/** 实时预览 */
function realTime(data: any) {
  options.previews = data
}
/** 上传预处理 */
function beforeUpload(file: any) {
  if (file.type.indexOf("image/") == -1) {
    showPromptMessage("error", "文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。")
  } else {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => {
      options.img = reader.result
      open.value = true
    }
  }
}

/** 关闭窗口 */
function closeDialog() {
  options.img = ""
  visible.value = false
}
/** 打开弹出层结束时的回调 */
function modalOpened() {
  visible.value = true
}

/** 上传图片 */
function uploadImg() {
  cropper.value.getCropBlob((data: any) => {
    imageUrl.value = URL.createObjectURL(data)
    open.value = false
    fileList.value[0] = data
  })
}
/** 覆盖默认上传行为 */
function requestUpload() {
  return new Promise(() => {})
}

const realName = ref("")
const showNameInput = ref(false)
const handleClickUpload = () => {
  showNameInput.value = true
}
const confirName = () => {
  if (userInfo.value?.name === realName.value) {
    dialogVisible.value = true
    showNameInput.value = false
    imageUrl.value = userInfo.value?.identificationPhotoUrl
  } else {
    showPromptMessage("error", "您输入的姓名不正确")
  }
}
</script>

<template>
  <div class="app-container">
    <el-card v-if="userInfo" shadow="never">
      <template #header>
        <div class="card-header">
          <span>学员信息</span>
        </div>
      </template>
      <div class="flex flex-col items-center">
        <div v-if="(userStore.userInfo as IStudentInfoData).identificationPhotoUrl" class="flex flex-col items-center">
          <el-image
            style="width: 100px; aspect-ratio: 22/32"
            :src="(userStore.userInfo as IStudentInfoData).identificationPhotoUrl"
            fit="cover"
          />
          <span class="mt-2">证件照</span>
        </div>
        <div v-else class="text-slate-300">无证件照</div>
        <el-form class="mt-5" label-position="left" label-width="80px" :model="userInfo" style="max-width: 460px">
          <el-form-item label="姓名">
            <el-input disabled v-model="userInfo.name" />
          </el-form-item>
          <el-form-item label="身份证号">
            <el-input disabled v-model="userInfo.identityCardId" />
          </el-form-item>
          <el-form-item label="性别">
            <el-input disabled v-model="userInfo.sex" />
          </el-form-item>
        </el-form>
        <div class="flex">
          <div>
            <el-button type="primary" @click="handleClickUpload">
              <el-icon>
                <Upload />
              </el-icon>
              <span class="ml-2"> 上传证件照 </span>
            </el-button>
          </div>

          <div class="ml-2">
            <el-button type="success" @click="passwordDialogVisible = true">
              <el-icon>
                <Switch />
              </el-icon>
              <span class="ml-2"> 修改密码 </span></el-button
            >
          </div>
        </div>
      </div>
    </el-card>
    <!--    证件照预览-->
    <el-dialog
      @closed="
        () => {
          imageUrl = ''
          uploadRef?.clearFiles()
        }
      "
      v-model="dialogVisible"
      title="上传证件照"
      width="30%"
      align-center
    >
      <div class="flex flex-col items-center">
        <div class="upload" df-x-c>
          <el-image :preview-src-list="[imageUrl]" class="w-full h-full" v-if="imageUrl" :src="imageUrl" fit="fill">
            <template #placeholder>
              <div class="w-full h-full flex justify-center items-center">加载中<span class="dot">...</span></div>
            </template></el-image
          >
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </div>
        <el-upload
          class="mt-2"
          accept=".png,.jpg,.jpeg"
          ref="uploadRef"
          :show-file-list="false"
          :before-upload="beforeUpload"
          action="#"
          :limit="1"
          :on-exceed="handleExceed"
        >
          <el-button type="primary">
            <el-icon>
              <Plus />
            </el-icon>
            <span class="ml-2"> 选择照片 </span>
          </el-button>
        </el-upload>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirm"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>

    <!--    修改密码-->
    <el-dialog @closed="resetPasswordForm" v-model="passwordDialogVisible" title="修改密码" width="30%" align-center>
      <div>
        <el-form
          :rules="rules"
          label-position="left"
          label-width="80px"
          ref="passwordFormRef"
          :model="changePasswordData"
          style="max-width: 460px"
        >
          <el-form-item label="新密码" prop="newPass">
            <el-input show-password v-model="changePasswordData.newPass" />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirm">
            <el-input show-password v-model="changePasswordData.confirm" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleChangePassword"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      title="自定义裁剪"
      v-model="open"
      width="1200px"
      append-to-body
      @opened="modalOpened"
      @close="closeDialog"
    >
      <el-row :gutter="20">
        <el-col :xs="24" :md="12" :style="{ height: '600px', width: '600px' }">
          <vue-cropper
            style="width: 100%; height: 100%"
            ref="cropper"
            :img="options.img"
            :info="true"
            :autoCrop="options.autoCrop"
            :autoCropWidth="options.autoCropWidth"
            :autoCropHeight="options.autoCropHeight"
            :fixedBox="options.fixedBox"
            :outputType="options.outputType"
            @realTime="realTime"
            v-if="visible"
          />
        </el-col>
        <el-col :xs="24" :md="12" :style="{ height: '350px' }">
          <div
            :style="{
              width: options.previews.w + 'px',
              height: options.previews.h + 'px'
            }"
            class="avatar-upload-preview overflow-hidden"
          >
            <img :src="options.previews.url" :style="options.previews.img" />
          </div>
        </el-col>
      </el-row>
      <br />
      <el-row>
        <el-col :lg="2" :md="2">
          <el-upload action="#" :http-request="requestUpload" :show-file-list="false" :before-upload="beforeUpload">
            <el-button>
              选择
              <el-icon class="el-icon--right"><Upload /></el-icon>
            </el-button>
          </el-upload>
        </el-col>

        <el-col :lg="{ span: 2, offset: 6 }" :md="2">
          <el-button type="primary" @click="uploadImg()">提 交</el-button>
        </el-col>
      </el-row>
    </el-dialog>

    <el-dialog
      @closed="
        () => {
          realName = ''
        }
      "
      title="提示"
      v-model="showNameInput"
      width="500px"
      ><div class="input-name-box">
        <span>本人</span>
        <el-input style="width: 100px" v-model="realName" />
        <span class="break-all">
          承诺：上传的照片为个人真实信息，证明书信息为本人学习经历，如有虚假，所造成后果由本人承担。
        </span>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-space>
            <el-button
              @click="
                () => {
                  showNameInput = false
                }
              "
              >取消</el-button
            >
            <el-button type="primary" @click="confirName">确认</el-button>
          </el-space>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.upload {
  border: 1px dashed var(--el-border-color);
  box-sizing: border-box;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 175px;
  aspect-ratio: 35/53;
  transition: var(--el-transition-duration-fast);
}

.upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.input-name-box {
  line-height: 40px;
}
.input-name-box :deep(.el-input) {
  border-bottom: 1px solid #ccc;
}
.input-name-box :deep(.el-input__wrapper) {
  box-shadow: none;
}
</style>
